/**
 * 递归遍历，每遍历一个节点计数加一
 * @param {TreeNode} root
 * @return {number}
 */
const countNodes = root => {
  const getNodeSum = node => {
    if (node === null) return 0
    let leftNums = getNodeSum(node.left),
      rightNums = getNodeSum(node.right)
    return leftNums + rightNums + 1
  }
  return getNodeSum(root)
}

const root = {
  val: 3,
  left: {
    val: 9,
    left: null,
    right: null
  },
  right: {
    val: 20,
    left: {
      val: 15,
      left: null,
      right: null
    },
    right: {
      val: 7,
      left: null,
      right: null
    }
  }
}

console.log(countNodes(root))